package com.xxh.video.aspect;

import com.xxh.common.utils.WebUtils;
import com.xxh.dataaccess.entity.log.UserLog;
import com.xxh.dataaccess.service.UserLogService;
import com.xxh.video.annotation.VideoAnnotation;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Aspect
@Component
public class LogAspect {


    @Autowired
    UserLogService userLogService;

    private static final Logger LOG = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 切点
     */
    @Pointcut("@annotation(com.xxh.video.annotation.VideoAnnotation)")
    public void operationLog() {

    }


    /**
     * 环绕增强，相当于MethodInterceptor
     */
    @Around("operationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            addOperationLog(joinPoint);
            return joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        } finally {
            System.out.println("around");
        }
    }

    /**
     * 方法执行完成后增加日志
     *
     * @param joinPoint
     */
    private void addOperationLog(JoinPoint joinPoint) {
        System.out.println("被执行");
        Map<String, Object> fieldsMap = getFieldsName((ProceedingJoinPoint) joinPoint);
        String bv = (String) fieldsMap.get("bv");
        UserLog log = new UserLog();
        log.setOperationDate(new Date());
        log.setBv(bv);
        VideoAnnotation annotation = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            annotation = method.getAnnotation(VideoAnnotation.class);
        } catch (Exception e) {
            LOG.error("获取当前类有 VideoAnnotation 注解的方法异常", e);
        }
        if (annotation != null) {
            switch (annotation.operationType()) {
                case FAV:
                    log.setFav(true);
                case LIKE:
                    log.setLike(true);
                case CLICK:
                    log.setClick(true);
            }
        }
        //TODO 这里保存日志
        Long userId = WebUtils.getUserId();
        if (null != userId) {
            log.setUid(userId);
            userLogService.saveUserLog(log);
            LOG.info("记录日志:" + log.toString());
        } else {
            LOG.info("当前用户未登录，日志不用记录");
        }
    }


    /**
     * 获取参数列表
     *
     * @param joinPoint
     * @return 参数列表
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     */
    private static Map<String, Object> getFieldsName(ProceedingJoinPoint joinPoint) {
        // 参数值
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = pnd.getParameterNames(method);
        Map<String, Object> paramMap = new HashMap<>(32);
        for (int i = 0; i < parameterNames.length; i++) {
            paramMap.put(parameterNames[i], args[i]);
        }
        return paramMap;
    }


}
